<?php
namespace App\Models;

use Hash;
use Request;
use Validator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\User
 *
 * @property int $id 用户编号
 * @property string $name 用户名称
 * @property string $password 密码
 * @property string $real_name 真实姓名
 * @property string $phone 手机号码
 * @property string $email 邮箱
 * @property string $register_time 注册时间
 * @property string $last_time 上次登录时间
 * @property string $address 用户地址
 * @property string $remember_token
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User wherePassword($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereRealName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User wherePhone($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereEmail($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereRegisterTime($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereLastTime($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereAddress($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereRememberToken($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class User extends Model
{
    use SoftDeletes;
    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'users';
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'password',
        'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * 软删除(回收站功能)
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * 注册API
     * @param Request $request
     * @return $this|array
     */
    public function signup(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|regex:/^([\w]{3,10})$/|unique:admins',
            'email' => 'required|regex:/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/|unique:admins',
            'password' => 'required|regex:/^((?=^.{6,12}$)(?=(?:.*?\d){1})(?=(?:.*?[a-z]){1})(?=(?:.*?[A-Z]){1})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*)$/',
            'confirm' => 'required|same:password'
        ], [
            'name.required' => '用户名不能为空',
            'name.unique' => '用户名已经存在',
            'name.regex' => '请填写3-10位,数字,字母,下划线',
            'email.required' => '邮箱不能为空',
            'email.unique' => '邮箱已被注册',
            'email.regex' => '邮箱格式不正确',
            'password.required' => '密码不能为空',
            'password.regex' => '请输入6-12位的密码.至少包含1位大写字母,小写字母,特殊符号,数字',
            'confirm.required' => '确认密码不能为空',
            'confirm.same' => '两次密码不一致'
        ]);
        if ($validator->fails()){
            $msg = $validator->errors()->all();
            return ['status' => -1, 'error' => $msg];
        }
        $data = $request->only(['name','email','password']);
        $user = $this;
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->password = Hash::make($data['password']);
        $user->status = '1';
        $user->remember_token = str_random(64);
        /*存入数据库*/
        if($user->save()){
            return ['status' => 1, 'msg' => '添加成功'];
        }else{
            return ['status' => 0, 'error' => '添加失败'];
        }
    }

    /**
     * 登录API
     * @param Request $request
     * @return array
     */
    public function login(Request $request)
    {
        /*调用公共方法获取用户名,密码*/
        $data = $request->only(['name','password']);

        /*判断登录信息是否为空*/
        if(!($data['name'] || $data['password']))
            return ['status' => 0, 'msg' => '用户名和密码不能为空'];
        elseif(!$data['name'])
            return ['status' => 0, 'msg' => '用户名不能为空'];
        elseif(!$data['password'])
            return ['status' => 0,'msg' => '密码不能为空'];

        /*把用户民,密码赋值给变量方便检测*/
        $name = $data['name'];
        $password = $data['password'];

        /*检验用户是否存在*/ /*$user是单条数据对象*/
        $admin = $this->where('name', $name)->first();
        if (!$admin)
            return ['status' => 0, 'msg' => '用户名不存在'];

        /*获取数据库密码*/
        $hashed_password = $admin->password;

        /*Hash检查比对登录密码*/
        if (!Hash::check($password,$hashed_password))
            return ['status' => 0, 'msg' => '密码有误'];

        /**将用户信息写入session*/
        session()->put('id',$admin->id);
        session()->put('name',$admin->name);
        return ['status' => 1,'msg' => '你已登录','id' => $admin->id];
    }

    /*登出API*/
    public function logout()
    {
        /*清空session*/
        session()->forget('id');
        session()->forget('name');
        return ['status' => 1,'msg' => '已经退出'];
    }


    /*修改信息*/
    public function edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|regex:/^([\w]{3,10})$/',
            'email' => 'required|regex:/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/',
        ],[
            'name.required' => '用户名不能为空',
            'name.regex' =>'用户名,请填写3-10位,数字,字母,下划线',

            'email.required' => '邮箱不能为空',
            'email.regex' => '邮箱格式不正确'
        ]);
        if($validator->fails()){
            $msg = $validator->errors()->all();
            return ['status' => -1, 'error' => $msg];
        }

        $data = $request->only(['name','email','status']);

        $user = $this->where('id', $request->get('id'))->first();

        try{
            if($user->update($data))
                return ['status' => 1, 'msg' => '修改成功'];
            else
                return ['status' => 0, 'msg' => '修改失败'];
        }catch (\Exception $exception){
            return ['status' => 0, 'msg' => '修改失败'];
        }
    }

    /*软删除(放入回收站回收站)*/
    public function adminDelete($id)
    {
        try{
            if(User::where('id',$id)->delete())
                return ['status' => 1, 'msg' => '删除成功'];
            else
                return ['status' => '0','msg' => '删除失败'];
        }catch (\Exception $exception){
            return ['status' => '0','msg' => '删除失败'];
        }
    }
}

